/**
 * Created by tdzl2003 on 7/28/16.
 */
import { exec } from 'child_process';

export function runCommand({script, workDir}) {
  return new Promise(resolve => {
    var env = {...process.env};
    delete env.name;
    delete env.cwd;
    delete env.pm_exec_path;
    delete env.pm_cwd;
    delete env.pm_out_log_path;
    delete env.pm_err_log_path;
    delete env.pm_pid_path;
    delete env.PM2_JSON_PROCESSING;
    delete env.PORT;
    delete env.pm_id;

    exec(script, {
      env,
      cwd: workDir,
      maxBuffer: 16*1024*1024,
    }, (err, stdout, stderr) => {
      if (err) {
        console.error(`exec error: ${err}`);
        resolve();
        return;
      }
      console.log(`${stdout}`);
      console.log(`${stderr}`);
      resolve();
    })

  });
}

const pendings = {};

export function pendingFilter(id, filter) {
  return pendings[id] = Promise.resolve(pendings[id])
    .then(() => runCommand(filter));
}